import * as React from 'react';
import * as html2canvas from "html2canvas"
import { withRouter } from 'react-router-dom';
import { getAssistant } from '../../services/assistant'
import Stat from './templates/Stat'
import Relation from './templates/Relation'
import './styles.less';
import DetailList from './templates/DetailList';
import News from './templates/News';
import { parse } from 'querystring';
import { PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import { getDocxAsBase64 } from '../../utils/base64Files';
import { showSelection, insertParagraph } from '../../utils/WordUtil';
import store from '../../utils/localStorage';

export interface AssistantProps {
}

export interface AssistantState {
  skill: string,
  keyword: any
  index: any
  list: any[],
  // recommodList: any[]
}

// 从弹窗 传入要搜索的关键词，跟预览时点击的哪一个

class Assistant extends React.Component<AssistantProps, AssistantState> {
  constructor(props, context) {
    super(props, context);
    const search = parse(props.location.search.replace('?', ''))
    const { keyword = '', index = '' } = search

    this.state = {
      skill: '',
      keyword,
      index,
      list: [],
      // recommodList: []
    };
  }

  componentDidMount() {
    const { keyword, index } = this.state
    this.onSearch(keyword, index)
  }

  onSearch = async (value, index) => {
    const result = await getAssistant(value)
    this.setState({
      skill: result.skill,
      list: [result.data[index]],
      // recommodList: result.relatedQuestions
    })

  }


  renderTemplate = (key, index, data, type?: string) => {
    let dom = null
    switch (key) {
      // 统计图
      case 'stat':
        dom = <Stat key={index} res={data} isNeedParent={false} />
        break;
      // 关系图
      case 'relation':
      case 'graph':
      case 'path':
      case 'timing':
        dom = <Relation key={index} res={data} keyword={key} isNeedParent={false} />
        break;
      // table
      case 'kb':
        if (type === 'detail-list') {
          dom = <DetailList key={index} res={data} isNeedParent={false} />
        }
        break;
      // 新闻
      case 'semanticsearch':
        dom = <News key={index} res={data} isNeedParent={false} />
        break;
      default:
        break;
    }
    return dom;
  }

  private insert = async key => {

    switch (key) {
      // 统计图
      case 'stat':
      case 'relation':
      case 'graph':
      case 'path':
      case 'timing':
        this.insertImg()
        break;
      default:
        Office.context.ui.messageParent(key);
        break;
    }

    // this.insertImg()
    // insertParagraph()
    this.test()
  };

  insertImg = async () => {
    try {
      const canvas = await html2canvas(document.querySelector("#chart"), { useCORS: true })
      const base64 = canvas.toDataURL("image/png")
      let newImg = base64.substr(base64.indexOf(",") + 1, base64.length)
      Office.context.ui.messageParent(newImg)
    } catch (error) {
      console.log('error', error)
    }

  }

  private test = () => {
    // 测试从弹窗传数据到 插件
    const testData = {
      title: '测试',
      content: getDocxAsBase64()
    }
    localStorage.setItem('sessionData', '')
    localStorage.setItem('sessionData', JSON.stringify(testData))
    console.log('插入localStorage')

    showSelection() // 测试失败直接不能获取 office context等属性
    console.info('Office', Office)
    console.info('Word', Word)
  };

  render() {
    const { skill, list = [] } = this.state
    console.log('编辑图表', list)
    return (
      <div className='container'>

        <div className="content-container">
          {list && list.length > 0 && list.map((item, index) => {
            const { type } = item.content
            return this.renderTemplate(skill, index, item, type)
          })}
        </div>
        {/* <div className="ms-clearfix" style={{ textAlign: 'center', marginTop: '15px' }}>
          <PrimaryButton className="pull-right" onClick={() => this.insert(skill)}>使用</PrimaryButton>
        </div> */}
      </div>
    );
  }

}

export default withRouter(Assistant)
